import {
  HTTP
} from '../util/http.js'

class ClassicModel extends HTTP {
  getLatest(sCallback) {
    this.request({
      url: 'classic/latest',
      success: (res) => {
        sCallback(res)
        this._setLatestIndex(res.index)
        // 把获取的最新期刊也写入缓存中
        let key = this._getKey(res.index)
        wx.setStorageSync(key, res)
      }
    })
  }

  getClassic(index, nextOrPrevious, sCallback) {
    // 首先确定缓存中所有期刊的key：通过私有方法_getKey()
    let key = nextOrPrevious == 'next' ? this._getKey(index + 1) : this._getKey(index - 1)
    // 要获取一个期刊时，首先到缓存中寻找，若缓存中有则读取出来
    let classic = wx.getStorageSync(key)
    // 没有则从服务器API中请求，同时写入缓存中
    if (!classic) {
      this.request({
        url: `classic/${index}/${nextOrPrevious}`, // 模板字符串
        success: (res) => {
          wx.setStorageSync(this._getKey(res.index), res)
          sCallback(res)
        }
      })
    } else {
      sCallback(classic)
    }
  }

  isFirst(index) {
    return index == 1 ? true : false
  }

  isLatest(index) {
    let latestIndex = this._getLatestIndex()
    return latestIndex == index ? true : false
  }

  // 把最新的期刊的index缓存起来
  _setLatestIndex(index) {
    wx.setStorageSync('latest', index)// 同步写入缓存（不追求性能，使用同步就行）
  }

  // 读取缓存值
  _getLatestIndex() {
    let index = wx.getStorageSync('latest')
    return index
  }

  _getKey(index) {
    let key = 'classic-' + index
    return key
  }
}

export {
  ClassicModel
}